<!-- eslint-disable no-undef -->
<template>
  <div class="map-wrapper">
    <!-- 用户头像 -->
    <el-dropdown class="user-avatar" trigger="click" @command="handleCommand">
      <el-avatar 
        :size="40" 
        :src="avatarUrl" 
        class="avatar-img"
      />
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="profile">修改个人信息</el-dropdown-item>
          <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

        <!-- 景点推荐 -->
   <el-button
    class="recommend-btn"
    type="primary"
    icon="Star"
    @click="goToRecommendations"
  >
    景点推荐
  </el-button>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
        v-model="searchText"
        placeholder="请输入地址或地点名称"
        clearable
        @keyup.enter="searchLocation"
      >
        <template #append>
          <el-button
            type="success"
            icon="Search"
            @click="searchLocation"
            class="custom-search-btn"
          >
            <span class="btn-text">搜索</span>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 地图容器 -->
    <div id="map-container"></div>

    <!-- 搜索框结果列表 -->
    <el-card
      v-if="searchResults.length"
      class="search-results"
    >
      <div
        v-for="(result, index) in searchResults"
        :key="index"
        class="search-result-item"
        @click="selectLocation(result)"
      >
        <div class="result-content">
          <el-text tag="b">{{ result.name }}</el-text>
          <el-text type="info" size="small">{{ result.address }}</el-text>
        </div>
      </div>
    </el-card>

    <!-- 景点弹窗 -->
    <el-dialog
      v-model="showAttractionDialog"
      title="周边景区"
      width="600px"
      :before-close="closeDialog"
    >
      <template #default>
        <div class="attraction-content">
          <el-skeleton :rows="3" animated v-if="loading" />
          <el-empty
            v-else-if="attractions?.length === 0"
            description="暂无景区信息"
          />
          <div v-else>
            <el-card
              v-for="attraction in attractions"
              :key="attraction.id"
              class="attraction-item"
              @click="viewDetail(attraction.id)"
            >
              <template #header>
                <div class="card-header">
                  <el-text tag="h4" class="title">{{ attraction.name }}</el-text>
                </div>
              </template>
              <el-text class="description">{{ attraction.description }}</el-text>
              <el-text type="info" size="small" class="address">
                <i class="el-icon-location"></i>
                {{ attraction.address }}
              </el-text>
            </el-card>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getNearbyAttractions } from '@/api/attractions.js'
import { userLogoutService } from '@/api/user'
import { ElLoading, ElMessage } from 'element-plus'

export default {
  name: 'AMap',
  setup() {
    const router = useRouter()
    const searchText = ref('')
    const map = ref(null)
    const currentMarker = ref(null)
    const searchResults = ref([])
    const attractions = ref([])
    const showAttractionDialog = ref(false)
    const loading = ref(false)
    const avatarUrl = ref('https://th.bing.com/th/id/OIP.g5M-iZUiocFCi9YAzojtRAAAAA?o=7&cb=iwp2rm=3&rs=1&pid=ImgDetMain')

    // 初始化地图
    const initMap = () => {
      if (typeof AMap !== 'undefined') {
        // eslint-disable-next-line no-undef
        map.value = new AMap.Map('map-container', {
          zoom: 12,
          center: [103.98845, 30.581839],
        })

        // 地图点击事件
        map.value.on('click', async (event) => {
          if (currentMarker.value) {
            map.value.remove(currentMarker.value)
          }

          const lng = event.lnglat.getLng()
          const lat = event.lnglat.getLat()

          try {
            loading.value = true
            showAttractionDialog.value = true

            const response = await getNearbyAttractions(lng, lat)
            attractions.value = response.data

            // eslint-disable-next-line no-undef
            currentMarker.value = new AMap.Marker({
              position: [lng, lat],
              title: '点击位置',
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            })
            map.value.add(currentMarker.value)
          } catch (error) {
            ElMessage.error('获取周边信息失败')
          } finally {
            loading.value = false
          }
        })

        // 初始化逆地理编码
        map.value.plugin('AMap.Geocoder', () => {
          // eslint-disable-next-line no-undef
          new AMap.Geocoder({
            city: "全国",
            radius: 1000
          })
        })

      } else {
        ElMessage.error('高德地图加载失败')
      }
    }

    // 地点搜索
    const searchLocation = () => {
      if (!searchText.value.trim()) return

      // eslint-disable-next-line no-undef
      AMap.plugin('AMap.PlaceSearch', () => {
        // eslint-disable-next-line no-undef
        const placeSearch = new AMap.PlaceSearch({
          city: '全国',
          pageSize: 10
        })

        placeSearch.search(searchText.value, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            searchResults.value = result.poiList?.pois || []
          }
        })
      })
    }

    // 选择搜索结果
    const selectLocation = (result) => {
      const center = [result.location.lng, result.location.lat]
      map.value.setCenter(center)
      map.value.setZoom(15)

      if (currentMarker.value) {
        map.value.remove(currentMarker.value)
      }

      // eslint-disable-next-line no-undef
      currentMarker.value = new AMap.Marker({
        position: center,
        title: result.name,
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      })
      map.value.add(currentMarker.value)
      searchResults.value = []
    }

    // 查看详情
    const viewDetail = async (id) => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在加载详情...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        await router.push(`/attraction/${id}`)
      } finally {
        loadingInstance.close()
      }
      closeDialog()
    }

    // 关闭弹窗
    const closeDialog = () => {
      showAttractionDialog.value = false
      attractions.value = []
    }

    // 用户操作处理
    const handleCommand = (command) => {
      if (command == 'profile') {
        router.push('/profile')
      } else if (command == 'logout') {
        handleLogout()
      }
    }


    // 退出登录
    const handleLogout = async () => {
      try {
        await userLogoutService()
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        router.push('/login')
        ElMessage.success('已退出登录')
      } catch {
        ElMessage.error('退出失败')
      }
    }

    //推荐跳转
    const goToRecommendations = () => {
       router.push('/recommendations')
    }
    onMounted(initMap)

    return {
      searchText,
      searchResults,
      attractions,
      showAttractionDialog,
      loading,
      avatarUrl,
      searchLocation,
      selectLocation,
      viewDetail,
      closeDialog,
      handleCommand,
      goToRecommendations
    }
  }
}
</script>

<style scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
}

#map-container {
  width: 100%;
  height: 100%;
}

.search-container {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 500px;
  z-index: 1000;
}

.user-avatar {
  position: absolute;
  top: 20px;
  right: 30px;
  z-index: 1001;
  cursor: pointer;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.1);
}

.avatar-img {
  border: 2px solid #fff;
}

.search-results {
  position: absolute;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 500px;
  max-height: 300px;
  overflow-y: auto;
  z-index: 1000;
}

.search-result-item {
  padding: 12px;
  border-bottom: 1px solid var(--el-border-color-light);
  cursor: pointer;
  transition: all 0.3s;
}

.search-result-item:hover {
  background-color: var(--el-color-primary-light-9);
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.attraction-content {
  height: 400px;
  overflow-y: auto;
}

.attraction-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.attraction-item:hover {
  box-shadow: var(--el-box-shadow-light);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  color: var(--el-color-primary);
}

.description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.address {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--el-text-color-secondary);
}
.recommend-btn {
  position: absolute;
  top: 20px;
  right: 90px; /* 调整位置避免与头像重叠 */
  z-index: 1001;
  padding: 8px 15px;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
</style>